package com.buss.admin.controller;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.hibernate.criterion.Restrictions;
import org.jweb.core.bean.PageMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.jweb.core.util.MyBeanUtils;
import org.jweb.core.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.buss.admin.entity.AdminEntity;
import com.buss.admin.trans.form.HXUserForm;
import com.buss.admin.trans.form.MemberForm;
import com.buss.common.model.json.EasyUIDataGridResult;
import com.buss.common.model.json.HXResult;
import com.buss.member.entity.GeneralUserEntity;
import com.buss.member.service.IMemberService;
import com.buss.member.util.StatusCode;

@Controller
@RequestMapping("admin/member")
public class AdminMemberController {

	@Autowired
	private IMemberService memberService;

	/*
	 * 查询所有会员列表并分页
	 */
	@RequestMapping("/list")
	@ResponseBody
	public EasyUIDataGridResult getMemberList(MemberForm searchForm) {

		// 分页查询
		CriteriaQuery cq = searchForm.getCriteriaQuery();

		/*
		 * 设置查询条件
		 */
		// cq.add(Restrictions.sizeGe("checkstatus", 10));
		cq.add(Restrictions.ge("checkstatus", 10));

		int pageNo = Integer.parseInt(searchForm.getPage());
		int pageSize = Integer.parseInt(searchForm.getRows());

		// 定义返回数据格式
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		PageMode<GeneralUserEntity> pageMode = memberService.list4page(cq, pageNo, pageSize);

		// 封装数据
		result.setRows(pageMode.getResult());
		result.setTotal(pageMode.getTotal());

		return result;

	}

	/**
	 * 根据Id值删除会员
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public HXResult deleteMemberById(String ids) {

		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				memberService.deleteEntityById(GeneralUserEntity.class, id);
			}

			return HXResult.ok("删除会员成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器发生错误，删除会员数据失败！");
		}

	}

	/**
	 * 更新会员信息
	 * 
	 * @param hxuser
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public HXResult updateMemberById(HXUserForm hxuser) {

		GeneralUserEntity member = new GeneralUserEntity();
		MyBeanUtils.copyBeanNotNull2Bean(hxuser, member);

		try {
			memberService.saveOrUpdate(member);
			return HXResult.ok("更新用户数据成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器发生错误，更新会员数据失败！");
		}
	}

	/**
	 * 在后台添加用户操作
	 * 
	 * @param hxuser
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public HXResult addMember(HXUserForm hxuser) {

		GeneralUserEntity member = new GeneralUserEntity();
		MyBeanUtils.copyBeanNotNull2Bean(hxuser, member);
		member.setCheckstatus(10);

		// 是否删除 0 可用 ， 1 删除
		member.setIsDelete(0);
		// Date joinTime = member.getJoinDate();
		// member.setUpdateInfoTime(joinTime);

		try {
			memberService.saveOrUpdate(member);

			return HXResult.ok("添加会员成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.ok("服务器发生错误，新增会员数据失败！");
		}

	}

	@RequestMapping("/registerCheck")
	@ResponseBody
	public HXResult registerCheck(String id, Integer status) {
		try {
			GeneralUserEntity user = memberService.getEntity(GeneralUserEntity.class, id);
			// 审核通过操作
			if (status == 1) {
				user.setCheckstatus(StatusCode.SC_10_YES);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户通过！");
				// 审核不通过操作
			} else if (status == 0) {
				user.setCheckstatus(StatusCode.SC_10_NO);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户不通过！");
			} else if (status == 3) {
				user.setCheckstatus(StatusCode.SC_1);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经还原用户状态！");
			}
			return HXResult.ok("系统服务异常，联系系统管理人员！");
		} catch (Exception e) {
			return HXResult.build(500, "服务器发生了异常，操作失败！");
		}
	}

	/**
	 * 管理员登录
	 * 
	 * @param session
	 * @param checkcode
	 * @param model
	 * @return
	 */
	@RequestMapping("/login")
	public String adminUserLogin(HttpSession session, String checkcode, AdminEntity model) {

		// 获取生成的验证码
		String key = (String) session.getAttribute("key");

		// 判断用户输入的验证码是否正确
		if (StringUtils.isNotBlank(checkcode) && checkcode.equals(key)) {
			// 验证码正确
			// 获得当前用户对象
			Subject subject = SecurityUtils.getSubject();
			String password = model.getPassword();

			// 对管理员用户的密码进行加密操作
			String passwrod = PasswordUtil.encrypt(password, PasswordUtil.str, PasswordUtil.getStaticSalt());
			// 构造一个用户名密码令牌
			AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), password);
			try {

				subject.login(token);
			} catch (UnknownAccountException e) {
				e.printStackTrace();
				return "redirect:/index.jsp";
			} catch (Exception e) {
				e.printStackTrace();
				return "redirect:/index.jsp";
			}
			// 获取认证信息对象中存储的User对象
			AdminEntity user = (AdminEntity) subject.getPrincipal();
			// 用户登录登录成功
			session.setAttribute("loginUser", user);
			return "redirect:/home.jsp";
		} else {
			return "redirect:/index.jsp";
		}
	}

	/*
	 * 管理员相关页面跳转
	 */
	@RequestMapping("/{path}")
	public String goPath(@PathVariable String path) {
		return "admin/member/" + path;
	}

}
